import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)
// 自定义路由映射
const routes = [
  // 登录路由
  {
    path: '/login',
    component: () => import('@/views/login'),
    meta: { title: '登录' }
  },
  // 主界面路由
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home',
    children: [
      { path: '/home', component: () => import('@/views/home'), meta: { title: '首页' } },
      { path: '/qa', component: () => import('@/views/qa'), meta: { title: '问答' } },
      { path: '/video', component: () => import('@/views/video'), meta: { title: '视频' } },
      { path: '/user', component: () => import('@/views/user'), meta: { title: '我的' } }
    ]
  },
  {
    path: '/user/shoucang',
    component: () => import('@/views/user/shoucang.vue'),
    meta: { title: '我的收藏', needLogin: true }
  },
  {
    path: '/user/lishi',
    component: () => import('@/views/user/lishi.vue'),
    meta: { title: '我的历史', needLogin: true }
  },
  {
    path: '/search',
    component: () => import('@/views/search'),
    meta: { title: '搜索' }
  },
  {
    path: '/article/:id',
    name: 'article',
    component: () => import('@/views/article'),
    meta: { title: '文章详情' },
    props: true // 开启解耦路由数据
  }
]

const router = new VueRouter({
  routes
})
// 导航守卫
router.beforeEach((to, from, next) => {
  document.title = to.meta.title
  // 登录的守卫
  // 判断去的页面是否需要登录，判断元信息里面是否有needLogin为true
  if (to.meta.needLogin) {
    // 需要登录才可以进入
    // 判断是否登录了
    if (store.getters.token) {
      // 登录了，放行
      next()
    } else {
      // 未登录，去登录页
      next('/login?url=' + to.path)
    }
  } else {
    // 不需要登录，直接放行
    next()
  }
})

export default router
